package com.yncmcc.Service;

import com.yncmcc.Entity.ContractsEntity;
import com.yncmcc.Entity.PeriodEntity;
import com.yncmcc.Repository.Interface.ContractsRepository;
import com.yncmcc.Repository.Interface.PeriodRepository;
import com.yncmcc.Service.Interface.PeriodService;
import com.yncmcc.Util.STATUS;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.commons.beanutils.converters.DoubleConverter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
//import java.sql.Timestamp;
import java.io.*;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by CMCC-sunmo on 2016/9/18.
 */
@Service("periodService")
@Transactional
public class PeriodServceImpl implements PeriodService {
    @Autowired
    private PeriodRepository periodRepository;
    private Map<String , Object> response;

    @Autowired
    private ContractsRepository contractsRepository;

    @Override
    public PeriodEntity[] findByRemindDate() {
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String periodRemindTime = sdf.format(new Date());
        Timestamp periodRemindTimeEnd = Timestamp.valueOf(periodRemindTime +" 23:59:59");
        Timestamp periodEndTimeBegin= Timestamp.valueOf(periodRemindTime +" 00:00:00");
        return periodRepository.findByRemindDate(periodRemindTimeEnd,periodEndTimeBegin);
    }

    @Override
    public String addPeriod(PeriodEntity periodEntity) {
        String message = "ok";

        ContractsEntity check = contractsRepository.findByContractID(periodEntity.getContractId());
        if(StringUtils.isBlank(periodEntity.getContractId())){
            message = "所要分期的合同ID不为空";
            return message;
        }else if(check == null){
            message = "所要分期的合同不存在";
            return message;
        }else if(StringUtils.isBlank(periodEntity.getPeriodMoney() + "")){
            message = "分期金额不为空";
            return message;
        }else if(periodEntity.getPeriodPaidTime() == null){
            message = "付款时间不为空";
            return message;
        }else if(periodEntity.getPeriodIsWarn() == 1){
            if(periodEntity.getPeriodRemindTime() == null){
                message = "提醒时间不为空";
                return message;
            } else if(periodEntity.getPeriodPaidTime().getTime() < periodEntity.getPeriodRemindTime().getTime()){
                message = "分期付款提醒时间不能大于付款时间";
                return message;
            }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        int random = (int)(Math.random()*10000);
        periodEntity.setPeriodId(sdf.format(new java.util.Date())+ random + "");
        periodEntity.setPeriodStatus(Short.parseShort("1"));
        periodEntity.setPeriodCTime(new Timestamp(System.currentTimeMillis()));
        periodRepository.save(periodEntity);
        return message;
    }

    @Override
    public String updatePeriod(PeriodEntity periodEntity) {
        String message = "ok";
        if(StringUtils.isBlank(periodEntity.getPeriodMoney() + "")){
            message = "分期金额不为空";
            return message;
        }else if(periodEntity.getPeriodPaidTime() == null){
            message = "付款时间不为空";
            return message;
        }else if(periodEntity.getPeriodIsWarn() == 1){
            if(periodEntity.getPeriodRemindTime() == null){
                message = "提醒时间不为空";
                return message;
            } else if(periodEntity.getPeriodPaidTime().getTime() < periodEntity.getPeriodRemindTime().getTime()){
                message = "分期付款提醒时间不能大于付款时间";
                return message;
            }
        }

        PeriodEntity period = periodRepository.findByperiodId(periodEntity.getPeriodId());
        period.setPeriodPaidTime(periodEntity.getPeriodPaidTime());
        period.setPeriodMoney(periodEntity.getPeriodMoney());
        period.setPeriodIsWarn(periodEntity.getPeriodIsWarn());
        if(periodEntity.getPeriodIsWarn() == 1){
            period.setPeriodRemindTime(periodEntity.getPeriodRemindTime());
        }
        periodRepository.saveAndFlush(period);
        return message;
    }

    @Override
    public List<PeriodEntity> findByContractId(String contractId) {
        return periodRepository.findByContractID(contractId);
    }

    @Override
    public String deletePeriodByContractId(String contractId) {
        String message = "ok";
        List<PeriodEntity> list = periodRepository.findByContractID(contractId);
        if(list != null && list.size() != 0){
            for (int i = 0 ; i < list.size() ; i++){
                PeriodEntity periodEntity = list.get(i);
                periodEntity.setPeriodStatus((short) 0);
                periodEntity.setPeriodDTime(new Timestamp(System.currentTimeMillis()));
                periodRepository.saveAndFlush(periodEntity);
            }
        }
        return message;
    }

    @Override
    public String addByExcel(MultipartFile file) throws IOException, BiffException {
        String message = "";
        File file1 = new File("temp");
        FileOutputStream fileOutputStream = new FileOutputStream(file1);
        BufferedOutputStream outputStream = new BufferedOutputStream(fileOutputStream);
        outputStream.write(file.getBytes());
        Workbook workbook = Workbook.getWorkbook(file1);

        int row;
        if(workbook.getNumberOfSheets()>1){
            Sheet sheet = workbook.getSheet(1);
            row = sheet.getRows();

            /* excel列顺序 */
            /* 合同ID */
            /* 付款时间 */
            /* 是否提醒 */
            /* 提醒时间 */
            /* 付款金额 */

            for (int i = 1; i < row; i++) {
                Cell cell = null;

                PeriodEntity periodEntity = new PeriodEntity();

                /* 分期ID及合同ID */
                if ((cell = sheet.getCell(0, i)) != null && !StringUtils.isBlank(cell.getContents())) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                    int random = (int)(Math.random()*10000);

                    periodEntity.setPeriodId(sdf.format(new java.util.Date()) + random + "");

                    ContractsEntity check = contractsRepository.findByContractSerial(cell.getContents());
                    if(check == null){
                        message = "Sheet2第" + (i+1) + "行：" + check.getContractId() + "合同编号不能为空";
                        return message;
                    }
                    periodEntity.setContractId(cell.getContents());

                } else {
                    message = "Sheet2第" + (i+1) + "行：合同编号不为空";
                    return message;
                }

                /* 付款时间 */
                if ((cell = sheet.getCell(1, i)) != null && !StringUtils.isBlank(cell.getContents())) {
                    String str = cell.getContents();
                    Timestamp timestamp = Timestamp.valueOf(str);
                    periodEntity.setPeriodPaidTime(timestamp);
                } else {
                    message = "Sheet2第" + (i+1) + "行分期付款时间不为空";
                    return message;
                }

                /* 分期是否提醒及提醒时间 */
                if ((cell = sheet.getCell(2, i)) != null && !StringUtils.isBlank(cell.getContents())) {
                    String str = cell.getContents();

                    if (str.equals("是")) {
                        periodEntity.setPeriodIsWarn(Short.parseShort("1"));
                        cell = sheet.getCell(3, i);

                        str = cell.getContents();
                        Timestamp timestamp = Timestamp.valueOf(str);
                        periodEntity.setPeriodRemindTime(timestamp);
                    } else {
                        periodEntity.setPeriodIsWarn(Short.parseShort("0"));
                    }
                } else {
                    message = "Sheet2第" + (i+1) + "行分期提醒时间不为空";
                    return message;
                }

                /* 付款金额 */
                if ((cell = sheet.getCell(4, i)) != null && !StringUtils.isBlank(cell.getContents())) {
                    String str = cell.getContents();

                    periodEntity.setPeriodMoney(Double.parseDouble(str));
                } else {
                    message = "Sheet2第" + (i+1) + "行：分期付款金额不为空";
                    return message;
                }

                /* 分期状态 */
                periodEntity.setPeriodStatus(Short.parseShort("1"));

                /* 分期创建时间 */
                /* 例：1999-09-09 12:12:12 */
                Timestamp date = new Timestamp(System.currentTimeMillis());
                periodEntity.setPeriodCTime(date);

                periodRepository.saveAndFlush(periodEntity);
            }
        }


        return message;
    }
}
